﻿using Sustainalytics.ClientDW.DataAccessLayer;
using Sustainalytics.DataLayer;
using Sustainalytics.Synchronization.Interface;
using System.Collections.Generic;

namespace Sustainalytics.Universes.Synchronization
{
    public class LoadFeatureUniversesSyncStep : ISyncStep
    {
        private IAccountsRepository _accountsRepository;
        private IUniversesRepository _universesRepository;
        private IClientDwRepository _clientDwRepository;

        public SyncStepOrder ExecutionOrder => SyncStepOrder.LoadFeatureUniverses;

        public SyncContext Start(SyncContext syncContext)
        {
            syncContext.Log("Connection strings: ClientPlatform = " + syncContext.GAConnectionStrings["ClientPlatform"]);
            syncContext.Log("Connection strings: ClientDW = " + syncContext.GAConnectionStrings["ClientDW"]);
            syncContext.Log("Connection strings: ClientDW = " + syncContext.GAConnectionStrings["ClientDW"]);

            _accountsRepository = AccountsRepository.GetAccountsRepository(syncContext.GAConnectionStrings["ClientPlatform"]);
            _universesRepository = UniversesRepository.GetUniversesRepository(syncContext.GAConnectionStrings["ClientUniverses"]);
            _clientDwRepository = ClientDwRepository.GetInstance(syncContext.GAConnectionStrings["ClientDW"]);

            var universeProcessing = UniverseSynchronization.GetInstance(_universesRepository, _accountsRepository, _clientDwRepository);

            universeProcessing.SyncUniverses(syncContext);

            var companyUniverses = _universesRepository.GetAllUniverseCompany();

            syncContext.CompanyUniverses = companyUniverses;

            syncContext.Log(string.Format("Dictionary CompanyUniverses has {0} elements.", syncContext.CompanyUniverses.Count));

            var changes = new List<ChangedElement>
                {
                    new ChangedElement
                    {
                        AffectedObjectName = "UniverseIds",
                        AffectedCollection = "All dependent",
                        AffectedDB = "ClientDW",
                        Operation = SyncOperation.Updated,
                        Status = SyncResultStatus.None
                    }
                };
            syncContext.Log("UniverseIds (ChangedElement) is added to syncContext.CurrentChanges");
            syncContext.AddManyChanges(changes);

            return syncContext;
        }
    }
}
